<?php
namespace Live\Controller;
use Live\Controller\CommonController;

$temp_arr = array();

class CommentController extends CommonController {
	public $pagesize=12;

	/**
	 * 评论管理
	 * @return [type] [description]
	 */
	public function index() {
		$group_id = I('get.group_id');

		$nickname = isset($_GET['nickname']) ? $_GET['nickname'] : '';
		$content = isset($_GET['content']) ? $_GET['content'] : '';

		$condition['live_group_id'] = $group_id;
		if($nickname) {
			$condition['username'] = $nickname;
		}
		if($content) {
			$condition['content'] = array('like', '%' . $content . '%');
		}

		$list = $this->getCommentByArticleId($group_id);

		//$htmlStr = $this->commentArr2Html($list);

        $count      = M('Comment')->where($condition)->count();

		$Page       = new \Think\Page($count,$this->pagesize);
		$show       = $Page->show();



		$this->assign('page', $show);
        $this->assign('title', $info['title']);
        $this->assign('commentList', $list);
		$this->display();
	}


	public function manage(){
        $group_id = I('get.group_id');

        $nickname = isset($_GET['nickname']) ? $_GET['nickname'] : '';
        $content = isset($_GET['content']) ? $_GET['content'] : '';
        $filter = isset($_GET['filter']) ? $_GET['filter'] : '';
        $condition['is_type']=0;
        if($group_id)
        $condition['live_group_id'] = $group_id;
        if($nickname) {
            $condition['username'] = $nickname;
        }
        if($content) {
            $condition['content'] = array('like', '%' . $content . '%');
        }

        if($filter!='' && $filter!=2) {
            $condition['is_verify'] = $filter;
        }
        $count      = M('Comment')->where($condition)->count();



        $Page       = new \Think\Page($count,$this->pagesize);
        $show       = $Page->show();



        $result = M('Comment')->where($condition)->order('is_delete asc, id desc')->page(I('get.p',1).",". 17)->select();
        foreach($result as $k=>$v){
            $result2=M('Live')->field('title')->where(array('group_id'=>$v['live_group_id']))->find();
            $result[$k]['title']=$result2['title'];
        }

        $this->assign('page', $show);
        $this->assign('title', $info['title']);
        $this->assign('commentList', $result);
        $this->display();
    }

	public function delCommentById() {
		$id = I('get.id');
		if($id) {
			$group_id = M('Comment')->where(array('id' => $id))->getField('live_group_id');
			// $list = $this->getCommentByArticleId($group_id);
			// $result = $this->findChildCommentId($list, $id);
			$list = $this->getCommentByArticleId($group_id);
			$ids = $this->findChildCommentId($list, $id);

			// print_r($ids);exit;

			$ids[] = $id;

			$res = M('Comment')->where(array('id' => array('in', $ids)))->save(array(
				'is_delete' => 1,
			));

			if($res !== false) {
				$WebSocketClient = new \Common\Util\PHPWebsocketClient('socket.appwuhan.net', '10088');
				$WebSocketClient->sendData(json_encode(array('action' => 'isBind', 'group' => $group_id)));
				$WebSocketClient->sendData(json_encode(array('action' => 'deleteComment', 'group' => $group_id, 'id' => $id)));
				$this->success('删除成功');
			} else {
				$this->error('删除失败');
			}

		} else {
			$this->error('删除失败');
		}
	}


	public function verifyCommentById() {
		$id = I('get.id');
		$status = I('get.status');
		if($id) {
			// $group_id = M('Comment')->where(array('id' => $id))->getField('live_group_id');
			$c_info = M('Comment')->where(array('id' => $id))->find();
			$group_id = $c_info['live_group_id'];
			$list = $this->getCommentByArticleId($group_id);
			$ids = $this->findChildCommentId($list, $id);

			$res = M('Comment')->where(array('id' => array('in', $id)))->save(array(
				'is_verify' => $status,
			));

			if($res !== false) {
				$WebSocketClient = new \Common\Util\PHPWebsocketClient('socket.appwuhan.net', '10088');
				if($status == 1) {
					$list = $this->getCommentByCommentId($group_id);

                    global $temp_arr;
                    
                    $temp_arr = array();

                    $comment = M('Comment')->where(array('id' => $id))->find();
					$userinfo = M("FrontUser")->where(array('front_user_id' => $comment['user_id']))->find();

					$ret_comment['id'] = (string) $id;
					$ret_comment['user_id'] = (string) $comment['user_id'];
					$ret_comment['username'] = $userinfo['nickname'] ? $userinfo['nickname'] : $comment['username'];
					$ret_comment['content'] = $comment['content']; 
					$ret_comment['color_type'] = (string) $comment['color']; // 颜色类型，1代表灰色
					$ret_comment['time'] = (string) $comment['time'];
					$ret_comment['avatar'] = $userinfo['avatar'] ? $userinfo['avatar'] : '';
					$ret_comment['pid'] = (string) $comment['pid'];


                    $this->addCommentNode($list, $ret_comment);
                    krsort($temp_arr);//根据key倒叙排序数组
                    $arr = array_values($temp_arr);
                    $result = $ret_comment;
                    $result['comments'] = $arr;
                    foreach($result as $k=>$v){
                        if($v===NULL){
                            $result[$k]="";
                        }
                    }
                    //dump($result);
					$WebSocketClient->sendData(json_encode(array('action' => 'passComment', 'group' => $group_id, 'data' => $result)));
				} else {
					$WebSocketClient->sendData(json_encode(array('action' => 'noComment', 'group' => $group_id, 'id' => $id, 'c_user_id' => $c_info['user_id'], 'c_content' => $c_info['content'])));				
				}

				$this->success('审核成功');
			} else {
				$this->error('服务器错误，请重试');
			}

		} else {
			$this->error('删除失败');
		}
	}


	/**
	 * 根据指定评论ID获取子评论
	 * @return [type] [description]
	 */
	protected function findChildCommentId($comment_arr, $id = 0) {
		$result = array();
		if(is_array($comment_arr) && !empty($comment_arr)){
			foreach ($comment_arr as $key => $value) {
				if($value['pid'] == $id) {
					$result[] = $value['id'];
					$tmp = $this->findChildCommentId($comment_arr, $value['id']);
					$result = array_merge($result, $tmp);
				}
			}
		}

		return $result;
	}

	/*
		获取文章id对应的所有评论，以数组的形式返回结果
	*/
	protected function getCommentByArticleId($articleid=1){
		$result = array();
		if(empty($articleid)){
			return $result;
		}

		$nickname = isset($_GET['nickname']) ? $_GET['nickname'] : '';
		$content = isset($_GET['content']) ? $_GET['content'] : '';

		$condition['live_group_id'] = $articleid;
		if($nickname) {
			$condition['username'] = $nickname;
		}
		if($content) {
			$condition['content'] = array('like', '%' . $content . '%');
		}

		$result = M('Comment')->where($condition)->order('is_delete asc, id desc')->page(I('get.p',1).",".$this->pagesize)->select();
		return $result;
	}

	protected function getCommentByCommentId($articleid=1){
		$result = array();
		if(empty($articleid)){
			return $result;
		}
		// ->field('*,if(is_verify=1,`content`,"您的评论未审核通过") as content')
		$result = M('Comment')->where(array('live_group_id' => $articleid))->order('is_delete asc, id desc')->select();

		return $result;
	}
	
	/*
		把评论数组数据转换为html格式
	*/
	protected function commentArr2Html($comment_arr) { 
	    $html_arr = array();
	    if(is_array($comment_arr) && !empty($comment_arr)){
	        // $str .= '<div id="commentHolder">'; 
	        foreach ($comment_arr as $key => $value) {
	        	$str = '';
	        	if($value['is_delete'] == 1) {
	         		$str .= '<div class="comment" style="background:#c1c1c1;">';
				} else {
	         		$str .= '<div class="comment">';
	         	} 	
	         	$str .= '<p class="title"><a class="tit" href="#">发布人：'. $value['username'] .'</a>';
	         	$str .= '<span>' . date('Y-m-d H:i:s', $value['time']) . ' 发表</span>';
	         	$str .= '</p>';

				global $temp_arr;
				$temp_arr = array();
			
				//这里去查找当前评论下的所有引用的评论，并格式化为html字符串
	         	$tmpStr = '';
	         	// print_r($value);echo '<br />';
	         	$this->addCommentNode($comment_arr, $value);
				krsort($temp_arr);//根据key倒叙排序数组
				$tmpStr = $this->getChildComment($temp_arr);//添加所有的引用评论
				$str .= $tmpStr;

	         	$str .= "<p>" . $value['content'] . "</p>";

	         	$str .= '<div class="oprea">';
	         	if($value['is_delete'] == 1) {
	         		$str .= '<span>删除状态：</span><a href="javascript:;" style="text-decoration:none; color: red;">已删除</a>';
	         	} else {
	         		$str .= '<span>删除操作：</span><a href="' . U('delCommentById') . '?id=' . $value['id'] . '" class="title">删除</a>';

		         	if($value['is_verify'] == 1) {
		         		$str .= '&nbsp;<span>审核操作：</span><a href="' . U('verifyCommentById') . '?id=' . $value['id'] . '&status=0" class="title">撤回</a>';
		         		$str .= '&nbsp;<span>审核状态：</span><a href="javascript:;" style="text-decoration:none; color: green;">已通过</a>';
		         	} else {
		         		$str .= '&nbsp;<span>审核操作：</span><a href="' . U('verifyCommentById') . '?id=' . $value['id'] . '&status=1" class="title">通过</a>';
		         		$str .= '&nbsp;<span>审核状态：</span><a href="javascript:;" style="text-decoration:none; color: red;">未通过</a>';
		         	}

	         	}

				$str .= '</div>';
	         	$str .= '</div>';
	         	$html_arr[] = $str;
	        }

	        // $str .='</div>';
	       
	    } 
	    return $html_arr; 
	} 
	
	/*
		把temp_arr数组中保存的引用评论信息转换为html形式
	*/
	protected function getChildComment($temp_arr){
		$htmlStr = '';
		if(!is_array($temp_arr) || empty($temp_arr)){
			return '';
		}
		foreach($temp_arr as $value){
			$tmp = '<div>';
			$tmp .= $htmlStr;
			$tmp .= '<span>' . $value['username'] . '  原贴：</span><br />' . $value['content'];
			$tmp .= '</div>';
			$htmlStr = $tmp;
		}
		return $htmlStr;

	}

	/*
		list代表某一文章下的全部评论列表
		cmt代表当前要显示的评论
	 */
	protected function addCommentNode($list, $cmt){
		if(isset($cmt['pid']) && $cmt['pid'] != '0'){

			$find = $this->findParentCmt($list, $cmt['pid']);//找寻id等于当前评论的pid的评论，返回数组。
			// 递归调用，只要pid不为零，就加入到引用评论列表
			$this->addCommentNode($list, $find);
		}else{
			return;
		}

	}

	/**
	 * 查找list中找寻id等于pid的数组项，并返回
	 * @param  [type] $list  [description]
	 * @param  [type] $cmtpid [description]
	 * @return [type]        [description]
	 */
	protected function findParentCmt($list, $cmtpid){
		foreach ($list as $key => $value) {
			if($value['id'] == $cmtpid){
				/* 用数组的方式来保存所有引用的评论 */
				global $temp_arr;
				$temp_arr[] = $list[$key];

				return $list[$key];
			}
		}
		return false;
	}
}